package com.UdpRecieve.domain;

import com.UdpRecieve.Netty.util.FileApproval.FileCheckType;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import com.monitorjbl.xlsx.StreamingReader;
import java.io.*;
import java.util.Map;

/**
 * 根据不同文件类型读取文件内容
 */
public class FileReadContent {

    /**
     * 根据word文件路径读取文件内容
     *
     * @param filePath 文件路径
     * @return 文件内容
     */
    public static String readDoc(String filePath) {
        String text = "文件内容";
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            Map<String, Object> mapResutlt = FileCheckType.getFileType(is);
            text = readDoc((InputStream) mapResutlt.get("inputStream"), (FileMagic) mapResutlt.get("fileMagic"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return text;
    }

    /**
     * 根据word文件流读取文件内容
     *
     * @param is 文件流
     * @return 文件内容
     */
    public static String readDoc(InputStream is, FileMagic fileMagic) {
        String text = "文件内容";
        try {
            if (fileMagic == FileMagic.OLE2) {
                WordExtractor ex = new WordExtractor(is);
                text = ex.getText();
                ex.close();
            } else if (fileMagic == FileMagic.OOXML) {
                XWPFDocument doc = new XWPFDocument(is);
                XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
                text = extractor.getText();
                extractor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return text;
    }

    /**
     * 根据excel文件路径读取文件内容
     *
     * @param filePath 文件路径
     * @return 文件内容
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
    public static String readExcel(String filePath) throws Exception {
        InputStream is = new FileInputStream(filePath);
        return readExcel(is, filePath);
    }

    /**
     * 根据excel文件流读取文件内容
     *
     * @param is       文件流
     * @param fileName 文件名
     * @return 文件内容
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
    public static String readExcel(InputStream is, String fileName) throws Exception {
        Workbook wb;
        StringBuilder sb = new StringBuilder();
        try {
            if (fileName.endsWith(".xls")) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = StreamingReader.builder()
                        .rowCacheSize(1000)    // number of rows to keep in memory (defaults to 10)
                        .bufferSize(4096)     // buffer size to use when reading InputStream to file (defaults to 1024)
                        .open(is);            // InputStream or File for XLSX file (required)
            }
            sb = readSheet(wb, sb, fileName.endsWith(".xls"));
            wb.close();
        } catch (OLE2NotOfficeXmlFileException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return sb.toString();
    }

    /**
     * 通过创建文件的方式读取excel文件
     *
     * @param filepath 文件路径
     * @param file     文件对象
     * @return 文件内容
     */
    public static String readExcelByFile(String filepath, File file) {
        Workbook wb = null;
        StringBuilder sb = new StringBuilder();
        try {
            if (filepath.endsWith(".xls")) {
                wb = WorkbookFactory.create(file);
            } else {
                wb = StreamingReader.builder()
                        .rowCacheSize(1000)    // number of rows to keep in memory (defaults to 10)
                        .bufferSize(4096)     // buffer size to use when reading InputStream to file (defaults to 1024)
                        .open(file);            // InputStream or File for XLSX file (required)
            }
            sb = readSheet(wb, sb, filepath.endsWith(".xls"));
            wb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                wb = null;
            }
        }
        return sb.toString();
    }

    /**
     * 读取excel文件中的sheet
     *
     * @param wb    Sheet
     * @param sb    内容容器
     * @param isXls execl文件判断标志
     * @return
     * @throws Exception
     */
    public static StringBuilder readSheet(Workbook wb, StringBuilder sb, boolean isXls) throws Exception {
        for (Sheet sheet : wb) {
            for (Row r : sheet) {
                for (Cell cell : r) {
                    if (cell.getCellType() == CellType.STRING) {
                        sb.append(cell.getStringCellValue());
                        sb.append(" ");
                    } else if (cell.getCellType() == CellType.NUMERIC) {
                        if (isXls) {
                            DataFormatter formatter = new DataFormatter();
                            sb.append(formatter.formatCellValue(cell));
                        } else {
                            sb.append(cell.getStringCellValue());
                        }
                        sb.append(" ");
                    }
                }
            }
        }
        return sb;
    }
}
